package cn.wolfcode.rbac.service.impl;

import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.domain.LoginUser;
import cn.wolfcode.rbac.domain.Permission;
import cn.wolfcode.rbac.mapper.EmployeeMapper;
import cn.wolfcode.rbac.mapper.PermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 改造前：EmployeeService查询直接查询数据库（匹配账号与密码）--得到Employee对象
 * 改造后：使用Spring security 那套用户操作规则-－需要重写UserDetailsService 里面loadUserByUsername 得到--UserDetails
 * EmployeeService 查询直接查询数据库（匹配账号与密码）--得到Employee对象
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 通过用户名， 查询Employee 库得到employee
        Employee employee = employeeMapper.selectByUsername(username);
        // 将employee封装成UserDetails---->也即：登录主体：LoginUser
        if (employee == null){
            return null;
        }
        // 查询用户所有的权限
        List<GrantedAuthority> list = new ArrayList<>();
        if (employee.getAdmin()){
            // 超管
            List<Permission> permissions = permissionMapper.selectAll();
            for (Permission permission : permissions) {
                list.add(new SimpleGrantedAuthority(permission.getExpression()));
            }
        }else{
            // 非超管
            List<String> permissions = permissionMapper.queryPermissionByEId(employee.getId());
            for (String permission : permissions) {
                list.add(new SimpleGrantedAuthority(permission));
            }
        }
        // 当前没有改造权限， 暂时让权限为null
        return new LoginUser(employee,list);
    }
}
